package com.xiaoma.guicedemo.module;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.xiaoma.guicedemo.test.CommunicationMain;
import com.xiaoma.guicedemo.communicator.Communicator;
import com.xiaoma.guicedemo.communicator.impl.AnotherCommunicatorImpl;
import com.xiaoma.guicedemo.communicator.impl.DefaultCommunicatorImpl;

/**
 * @author xiaoma
 * @date 2020-04-27 16:39
 */
public class BasicModule extends AbstractModule {

    @Override
    protected void configure() {
        // 表明：当需要 Communicator 这个变量时，我们注入 DefaultCommunicatorImpl 的实例作为依赖
        bind(Communicator.class).to(DefaultCommunicatorImpl.class);

//        bind(Communicator.class).annotatedWith(Names.named("communicator")).to(DefaultCommunicatorImpl.class);

        bind(CommunicationMain.class).toInstance(new CommunicationMain(true));


    }

    @Provides
    @Singleton
    @Named("communicator")//接口有多个实现，使用Named来标识唯一性
    public Communicator getCommunicator() {
        return new DefaultCommunicatorImpl();
    }

    /**
     * 提供一个对象
     * 参考: https://github.com/google/guice/wiki/ProvidesMethods
     * When you need code to create an object, use an @Provides method.
     * @param: []
     * @return: com.xiaoma.guicedemo.communicator.Communicator
     * @author: maj
     * @date: 2020/4/29 13:41
     */
    @Provides
    @Singleton
    @Named("anotherCommunicator")
    public Communicator getAnotherCommunicatorImpl() {
        return new AnotherCommunicatorImpl();
    }
}